﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GestorSQL.DataBase.Interface;
using System.IO;
using GestorSQL.BusinessEntities;
using GestorSQL.DAO.FileManager;
using GestorSQL.BLL.ImplementationsBridge;
using System.Data.Common;
using GestorSQL.DAO;

namespace GestorSQL.BLL.QueryExecutions
{
    public class BLLCommand : IDisposable
    {
        #region Variables Privadas
        private IDataBaseProvider dataManager;
        private IFileManager fileManager = null;
        private ConnectionManager connectionManager = new ConnectionManager();
        private QueryManager _queryManager = new QueryManager();
        private IGestorSqlDao dao = new GestorSqlDao();
        private BLLReader bllReader = null;
        private string currentQuery;
        private Caso caso = null;
        private string _comentarioEjecucion = string.Empty;
        #endregion

        #region Propiedades

        /// <summary>
        /// Establece el comentario de la ejecución
        /// </summary>
        public string ComentarioEjecucion { set { _comentarioEjecucion = value; } }

        #endregion

        #region Metodos Publicos
        public BLLCommand(Caso caso)
        {
            this.caso = caso;
            Conexion conexion = null;

            if (caso.IsProduction(caso.Historia.Estado_))
                conexion = dao.GetConnection(caso.Conexion1.IdConexion);
            else
                conexion = dao.GetConnection(caso.Conexion.IdConexion);

            dataManager = ImplementationBridge.GetDataBaseImplementationByCore(conexion.Fk_Core);
            dataManager.ConnectionString = connectionManager.GetConnectionStringByConnection(conexion);
            fileManager = ImplementationBridge.GetFileManager("Compress");

        }

        public BLLReader ExecuteQuery(string query)
        {
            currentQuery = query;
            return bllReader = new BLLReader(dataManager.Execute(query), caso, dataManager.OmitFirstResult, dataManager.OmitLastResult, dataManager.LastResultColumnName);
        }

        public void OpenConnection()
        {
            dataManager.Open();
        }

        public void BeginTransaction()
        {
            dataManager.BeginTransction();
        }

        public void CommitTransaction()
        {
            dataManager.RollbackTransaction();
        }

        public void RollbackTransaction()
        {
            dataManager.RollbackTransaction();
        }

        public void Dispose()
        {
            dataManager.Dispose();
            Close();
        }

        public void Close()
        {
            _queryManager.SaveQueryExecution(bllReader, this.caso, currentQuery, _comentarioEjecucion);
        }

        #endregion

    }
}
